<template>
  <div class="component-test">
    <el-card class="test-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h2>组件测试页面</h2>
          <el-tag type="success">BaseTable & AdvancedTable 组件测试</el-tag>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" type="border-card">
        <!-- BaseTable 测试 -->
        <el-tab-pane label="BaseTable 组件测试" name="base">
          <div class="tab-content">
            <h3>BaseTable 基础用法</h3>
            <p>BaseTable 是一个基础的表格组件，提供了基本的表格功能。</p>
            
            <el-card shadow="hover" class="example-card">
              <template #header>
                <div class="example-header">
                  <span>基础表格示例</span>
                  <el-button size="small" @click="refreshBaseTable">刷新数据</el-button>
                </div>
              </template>
              
              <BaseTable
                :data="baseTableData"
                :columns="baseTableColumns"
                :loading="baseTableLoading"
                :show-selection="true"
                :show-index="true"
                :bordered="true"
                :stripe="true"
                :total="baseTableData.length"
                @selection-change="handleBaseTableSelectionChange"
                @row-click="handleBaseTableRowClick"
                @sort-change="handleBaseTableSortChange"
              />
            </el-card>
            
            <el-card shadow="hover" class="example-card" style="margin-top: 20px;">
              <template #header>
                <div class="example-header">
                  <span>带分页的基础表格示例</span>
                </div>
              </template>
              
              <BaseTable
                :data="paginatedBaseTableData"
                :columns="baseTableColumns"
                :loading="baseTableLoading"
                :show-selection="true"
                :show-pagination="true"
                :total="100"
                :current-page="baseTablePagination.currentPage"
                :page-size="baseTablePagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                @selection-change="handleBaseTableSelectionChange"
                @row-click="handleBaseTableRowClick"
                @sort-change="handleBaseTableSortChange"
                @update:current-page="handleBaseTablePageChange"
                @update:page-size="handleBaseTableSizeChange"
              />
            </el-card>
          </div>
        </el-tab-pane>
        
        <!-- AdvancedTable 测试 -->
        <el-tab-pane label="AdvancedTable 组件测试" name="advanced">
          <div class="tab-content">
            <h3>AdvancedTable 高级用法</h3>
            <p>AdvancedTable 是基于 BaseTable 的高级表格组件，提供了更多功能和更好的用户体验。</p>
            
            <el-card shadow="hover" class="example-card">
              <template #header>
                <div class="example-header">
                  <span>高级表格示例</span>
                  <div>
                    <el-button size="small" @click="refreshAdvancedTable">刷新数据</el-button>
                    <el-button size="small" @click="toggleViewMode">
                      切换视图 (当前: {{ viewMode === 'table' ? '表格' : '卡片' }})
                    </el-button>
                  </div>
                </div>
              </template>
              
              <AdvancedTable
                :data="advancedTableData"
                :columns="advancedTableColumns"
                :loading="advancedTableLoading"
                :pagination="advancedTablePagination"
                :selected-items="selectedAdvancedItems"
                :show-view-toggle="true"
                :show-column-settings="true"
                :show-toolbar="true"
                :show-refresh="true"
                row-key="id"
                @selection-change="handleAdvancedTableSelectionChange"
                @row-click="handleAdvancedTableRowClick"
                @sort-change="handleAdvancedTableSortChange"
                @size-change="handleAdvancedTableSizeChange"
                @current-change="handleAdvancedTablePageChange"
                @refresh="refreshAdvancedTable"
                @view-mode-change="handleViewModeChange"
              >
                <!-- 自定义状态列 -->
                <template #status="{ row }">
                  <el-tag :type="getStatusTagType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
                
                <!-- 自定义评分列 -->
                <template #rating="{ row }">
                  <el-rate
                    v-model="row.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}分"
                  />
                </template>
                
                <!-- 自定义操作列 -->
                <template #actions="{ row }">
                  <el-button size="small" type="primary" @click.stop="editItem(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click.stop="deleteItem(row)">删除</el-button>
                </template>
                
                <!-- 卡片视图插槽 -->
                <template #card="{ row, index }">
                  <el-card shadow="hover" class="custom-card">
                    <div class="card-content">
                      <div class="card-header">
                        <h4>{{ row.name }}</h4>
                        <el-tag :type="getStatusTagType(row.status)">
                          {{ getStatusText(row.status) }}
                        </el-tag>
                      </div>
                      <div class="card-body">
                        <p><strong>联系人:</strong> {{ row.contactPerson || '-' }}</p>
                        <p><strong>电话:</strong> {{ row.phone || '-' }}</p>
                        <p><strong>邮箱:</strong> {{ row.email || '-' }}</p>
                        <p><strong>地址:</strong> {{ row.address || '-' }}</p>
                        <div class="rating-section">
                          <strong>评分:</strong>
                          <el-rate
                            v-model="row.rating"
                            disabled
                            show-score
                            text-color="#ff9900"
                            score-template="{value}分"
                          />
                        </div>
                      </div>
                      <div class="card-footer">
                        <el-button size="small" type="primary" @click.stop="editItem(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click.stop="deleteItem(row)">删除</el-button>
                      </div>
                    </div>
                  </el-card>
                </template>
              </AdvancedTable>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑项目"
      width="500px"
    >
      <el-form :model="editingItem" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editingItem.name" />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="editingItem.contactPerson" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editingItem.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editingItem.email" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editingItem.status" placeholder="请选择状态">
            <el-option label="激活" value="active" />
            <el-option label="待审核" value="pending" />
            <el-option label="停用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import BaseTable from '@/components/BaseTable.vue'
import AdvancedTable from '@/components/AdvancedTable.vue'

// 响应式数据
const activeTab = ref('base')
const viewMode = ref<'table' | 'card'>('table')
const editDialogVisible = ref(false)

// BaseTable 相关数据
const baseTableLoading = ref(false)
const baseTableData = ref<any[]>([])
const selectedBaseItems = ref<any[]>([])

const baseTablePagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 100
})

// AdvancedTable 相关数据
const advancedTableLoading = ref(false)
const advancedTableData = ref<any[]>([])
const selectedAdvancedItems = ref<any[]>([])
const editingItem = ref<any>({})

const advancedTablePagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 100,
  pageSizes: [10, 20, 30, 50, 100],
  layout: 'total, sizes, prev, pager, next, jumper'
})

// 表格列定义
const baseTableColumns = [
  { prop: 'name', label: '名称', minWidth: 150, sortable: true },
  { prop: 'contactPerson', label: '联系人', width: 120 },
  { prop: 'phone', label: '电话', width: 150 },
  { prop: 'email', label: '邮箱', width: 200 },
  { prop: 'status', label: '状态', width: 100, sortable: true }
]

const advancedTableColumns = [
  { type: 'selection', width: 50, fixed: 'left' },
  { prop: 'name', label: '名称', minWidth: 180, sortable: true, fixed: 'left' },
  { prop: 'contactPerson', label: '联系人', width: 120 },
  { prop: 'phone', label: '电话', width: 150 },
  { prop: 'email', label: '邮箱', width: 200 },
  { prop: 'status', label: '状态', width: 100, sortable: true, slot: 'status' },
  { prop: 'rating', label: '评分', width: 150, slot: 'rating' },
  { prop: 'actions', label: '操作', width: 150, fixed: 'right', slot: 'actions' }
]

// 计算属性
const paginatedBaseTableData = computed(() => {
  const start = (baseTablePagination.currentPage - 1) * baseTablePagination.pageSize
  return baseTableData.value.slice(start, start + baseTablePagination.pageSize)
})

// 方法
const refreshBaseTable = async () => {
  baseTableLoading.value = true
  try {
    console.log('开始刷新基础表格数据');
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 生成模拟数据
    baseTableData.value = Array.from({ length: 50 }, (_, i) => ({
      id: i + 1,
      name: `基础数据${i + 1}`,
      contactPerson: `联系人${i + 1}`,
      phone: `138${String(i + 1).padStart(8, '0')}`,
      email: `contact${i + 1}@example.com`,
      status: ['active', 'pending', 'inactive'][i % 3]
    }))
    
    console.log('基础表格数据刷新成功，数据长度:', baseTableData.value.length);
    ElMessage.success('基础表格数据刷新成功')
  } catch (error) {
    console.error('基础表格数据刷新失败:', error);
    ElMessage.error('刷新失败')
  } finally {
    baseTableLoading.value = false
  }
}

const refreshAdvancedTable = async () => {
  advancedTableLoading.value = true
  try {
    console.log('开始刷新高级表格数据');
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 生成模拟数据
    advancedTableData.value = Array.from({ length: 50 }, (_, i) => ({
      id: i + 1,
      name: `高级数据${i + 1}`,
      contactPerson: `联系人${i + 1}`,
      phone: `139${String(i + 1).padStart(8, '0')}`,
      email: `advanced${i + 1}@example.com`,
      address: `地址${i + 1}`,
      status: ['active', 'pending', 'inactive'][i % 3],
      rating: (Math.random() * 4 + 1).toFixed(1)
    }))
    
    console.log('高级表格数据刷新成功，数据长度:', advancedTableData.value.length);
    ElMessage.success('高级表格数据刷新成功')
  } catch (error) {
    console.error('高级表格数据刷新失败:', error);
    ElMessage.error('刷新失败')
  } finally {
    advancedTableLoading.value = false
  }
}

const toggleViewMode = () => {
  viewMode.value = viewMode.value === 'table' ? 'card' : 'table'
}

// 事件处理
const handleBaseTableSelectionChange = (selection: any[]) => {
  selectedBaseItems.value = selection
  console.log('BaseTable 选中项:', selection)
}

const handleBaseTableRowClick = (row: any) => {
  console.log('BaseTable 行点击:', row)
  ElMessage.info(`点击了基础表格行: ${row.name}`)
}

const handleBaseTableSortChange = (sort: { column: any; prop: string; order: string }) => {
  console.log('BaseTable 排序变化:', sort)
  ElMessage.info(`基础表格按 ${sort.prop} ${sort.order} 排序`)
}

const handleBaseTablePageChange = (page: number) => {
  baseTablePagination.currentPage = page
  console.log('BaseTable 页码变化:', page)
}

const handleBaseTableSizeChange = (size: number) => {
  baseTablePagination.pageSize = size
  baseTablePagination.currentPage = 1
  console.log('BaseTable 页面大小变化:', size)
}

const handleAdvancedTableSelectionChange = (selection: any[]) => {
  selectedAdvancedItems.value = selection
  console.log('AdvancedTable 选中项:', selection)
  ElMessage.info(`高级表格选中 ${selection.length} 项`)
}

const handleAdvancedTableRowClick = (row: any) => {
  console.log('AdvancedTable 行点击:', row)
  ElMessage.info(`点击了高级表格行: ${row.name}`)
}

const handleAdvancedTableSortChange = (sort: { prop: string; order: string }) => {
  console.log('AdvancedTable 排序变化:', sort)
  ElMessage.info(`高级表格按 ${sort.prop} ${sort.order} 排序`)
}

const handleAdvancedTablePageChange = (page: number) => {
  advancedTablePagination.currentPage = page
  console.log('AdvancedTable 页码变化:', page)
}

const handleAdvancedTableSizeChange = (size: number) => {
  advancedTablePagination.pageSize = size
  advancedTablePagination.currentPage = 1
  console.log('AdvancedTable 页面大小变化:', size)
}

const handleViewModeChange = (mode: 'table' | 'card') => {
  viewMode.value = mode
  console.log('视图模式变化:', mode)
}

const editItem = (row: any) => {
  editingItem.value = { ...row }
  editDialogVisible.value = true
}

const deleteItem = (row: any) => {
  ElMessageBox.confirm(`确定要删除 "${row.name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除操作
    ElMessage.success(`"${row.name}" 删除成功`)
  }).catch(() => {
    // 用户取消删除
  })
}

const saveEdit = () => {
  // 模拟保存操作
  ElMessage.success('保存成功')
  editDialogVisible.value = false
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'active': return '激活'
    case 'pending': return '待审核'
    case 'inactive': return '停用'
    default: return '未知'
  }
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'active': return 'success'
    case 'pending': return 'warning'
    case 'inactive': return 'danger'
    default: return 'info'
  }
}

// 初始化数据
onMounted(() => {
  console.log('组件测试页面挂载，开始加载数据');
  refreshBaseTable()
  refreshAdvancedTable()
})
</script>

<style scoped lang="scss">
.component-test {
  padding: 20px;
  
  .test-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .tab-content {
    padding: 20px 0;
    
    h3 {
      margin-bottom: 15px;
      color: #303133;
    }
    
    p {
      color: #606266;
      margin-bottom: 20px;
    }
  }
  
  .example-card {
    .example-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .custom-card {
    .card-content {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
      }
      
      .card-body {
        p {
          margin: 8px 0;
          font-size: 14px;
        }
        
        .rating-section {
          display: flex;
          align-items: center;
          gap: 10px;
          margin-top: 10px;
        }
      }
      
      .card-footer {
        margin-top: 15px;
        text-align: right;
      }
    }
  }
}
</style>